<template>
  <view class="match-major">
    <view class="filter-list">
      <view
        v-if="!hideFilters"
        :class="{
          'major-level': true,
          selected: currentLevelText != '专业层次'
        }"
        @click="showPicker('majorLevel')"
        >{{ currentLevelText }}</view
      >
      <view
        v-if="!hideFilters"
        :class="{ 'major-type': true, selected: currentTypeText != '专业类别' }"
        @click="showPicker('majorType')"
        >{{ currentTypeText }}
      </view>
      <view class="search-major" :class="{ expanded: hideFilters }">
        <input
          type="text"
          v-model="matchName"
          placeholder="查专业"
          @focus="handleFocus"
          @blur="handleBlur"
          @change="handleInputChange"
        />
      </view>
    </view>
    <view class="main">
      <view class="main-options">
        <view class="main-options-list">
          <view
            :class="{
              'main-options-list-item': true,
              selected: currentOptionValue == item.title
            }"
            v-for="(item, index) in matchLevelList"
            :key="index"
            @click="handleMainOptionClick(item, index)"
          >
            <text>{{ item.title }}</text>
            <text>({{ item.num || 0 }})</text>
          </view>
        </view>
      </view>
      <view class="introduce-content"
        >*符合{{ currentLevelText
        }}<span v-if="currentWholeTypeText != ''"
          >、{{ currentWholeTypeText }}</span
        >的专业有{{ matchMajorNum }}个</view
      >
      <view class="main-content">
        <scroll-view
          class="main-content-list"
          :scroll-y="true"
          :scroll-with-animation="true"
          v-if="contentList.length > 0"
        >
          <view
            class="main-content-list-item"
            v-for="(item, index) in contentList"
            :key="index"
          >
            <view class="item-title">
              {{ item.tagName }}
            </view>
            <view class="item-list">
              <view
                class="item-list-item"
                v-for="(_item, _index) in item.children"
                :key="_index"
                @click="jumpToMajorDeatil(_item, item)"
              >
                <text class="item-list-item-label">{{ _item.tagName }}</text>
                <text class="item-list-item-value"
                  >匹配率:{{ _item.score ? _item.score + '%' : '--' }}</text
                >
              </view>
            </view>
          </view>
        </scroll-view>
        <view class="main-content-empty" v-else>
          <Empty
            :baseImg="emptyImg"
            text="暂无匹配专业"
            textColor="#888"
            :fontWeight="400"
          />
        </view>
      </view>
    </view>
    <u-picker
      mode="selector"
      v-model="showMajorLevelPicker"
      :range="majorLevelOptions"
      range-key="cateName"
      @confirm="handleMajorLevelConfirm($event, item)"
      z-index="99999"
    ></u-picker>
    <u-select
      mode="mutil-column-auto"
      v-model="showMajorTypePicker"
      :list="majorTypeOptions"
      label-name="tagName"
      value-name="positionTagId"
      @confirm="handleMajorTypeConfirm($event, item)"
      z-index="99999"
    ></u-select>
  </view>
</template>

<script>
import { getAllPositionTagTree } from '@/api/modules/major';
import { collegeProfessionGetTagScore } from '@/api/modules/career';
import Empty from '@/components/Empty.vue';
export default {
  name: 'MatchMajor',
  components: {
    Empty
  },
  props: {
    relSubject: {
      type: String,
      required: true
    },
    positionId: {
      type: String,
      required: true
    },
    currentSubject: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      matchMajorNum: 0,
      matchName: '',
      currentLevelText: '本科',
      currentLevelValue: '30', //mock默认参数
      currentTypeText: '专业类别',
      currentWholeTypeText: '',
      currentTypeValue: '',
      currentTypeValueFirst: '',
      currentOptionValue: '1', //高匹配，中匹配的选项值
      hideFilters: false,
      showMajorLevelPicker: false,
      showMajorTypePicker: false,
      loading: false,
      contentList: [],
      matchLevelList: [], //这个是一级！！contentList是二三级！
      majorLevelOptions: [
        {
          cateName: '专科(高职)',
          id: '10'
        },
        {
          cateName: '本科',
          id: '30'
        }
      ],
      majorTypeOptions: [],
      emptyImg: this.$imgBaseSelf + 'common/empty.png'
    };
  },
  watch: {
    relSubject(newValue, oldValue) {
      if (this.positionId && newValue) {
        this.getMatchMajorDataFn();
      }
    },
    positionId(newValue, oldValue) {
      if (this.relSubject && newValue) {
        this.getMatchMajorDataFn();
      }
    }
  },
  created() {
    this.getAllPositionTagTreeList();
  },
  methods: {
    jumpToMajorDeatil(item, parentItem) {
      // uni.navigateTo({
      //   url:
      //     `/pagesSub/careerNew/majorDetail/index?positionTagId=` +
      //     item.positionTagId,
      // });
      // 序列化对象为查询字符串
      let tempInfo = {
        subjectCombination: this.relSubject.replace('、', ','),
        currentSubject: this.currentSubject.replace(/、/g, ','),
        secondName: parentItem.tagName, // 二级专业名称
        name: item.tagName, // 三级专业名称
        positionTagId: item.positionTagId,
        parentId: parentItem.positionTagId
      };
      const positionInfo = Object.keys(tempInfo)
        .map(
          (key) =>
            `${encodeURIComponent(key)}=${encodeURIComponent(tempInfo[key])}`
        )
        .join('&');
      uni.navigateTo({
        url: `/pagesSub/nationalCollegeEntranceExamination/majorDetail/index?${positionInfo}`
      });
    },
    showPicker(params) {
      switch (params) {
        case 'majorLevel':
          this.showMajorLevelPicker = true;
          break;
        case 'majorType':
          this.showMajorTypePicker = true;
          break;
        default:
          break;
      }
    },
    handleMajorLevelConfirm(e, item) {
      // e[0]就是索引
      this.currentLevelText = this.majorLevelOptions[e[0]].cateName;
      this.$emit('changeLevel', this.currentLevelText);
      this.currentLevelValue = this.majorLevelOptions[e[0]].id;
      this.currentTypeText = '专业类别';
      this.currentWholeTypeText = '';
      this.currentTypeValue = '';
      this.getAllPositionTagTreeList();
      this.getMatchMajorDataFn();
    },
    handleMajorTypeConfirm(e, item) {
      // e[0]就是索引
      const firstType = e[0];
      const secondType = e[1];
      this.currentWholeTypeText = secondType.label;
      this.currentTypeText =
        secondType.label.length > 4
          ? secondType.label.slice(0, 4) + '...'
          : secondType.label;
      this.currentTypeValue = secondType.value;
      this.currentTypeValueFirst = firstType.value;
      this.getMatchMajorDataFn();
    },
    handleInputChange(e) {
      console.log('handleInputChange', e);
      this.getMatchMajorDataFn();
    },
    handleFocus() {
      this.hideFilters = true; // 隐藏左侧筛选条件
      // 添加宽度变化的过渡动画
      // 你可以在这里调整动画效果
    },
    handleBlur() {
      this.hideFilters = false; // 显示左侧筛选条件
      // this.getAllProfessionFn();
      // 可以添加一些延迟来平滑过渡
      // setTimeout(() => {
      //   this.hideFilters = false;
      // }, 300);
    },
    //点击匹配度的筛选
    handleMainOptionClick(item, index) {
      this.currentOptionValue = item.title;
      this.matchMajorNum = this.matchLevelList[index].num;
      this.contentList = item.list;
      // this.getMatchMajorDataFn();
    },
    //获取结果列表
    getMatchMajorDataFn() {
      if (!(this.positionId && this.relSubject) || this.loading) {
        return;
      }
      this.loading = true;
      const params = {
        positionId: this.positionId,
        subjectCombination: this.relSubject.replace('、', ','),
        cpType: this.currentLevelValue, //10 高职专科   30 普通本科
        tagName: this.matchName, //模糊搜索专业名字
        tagId: ''
      };
      if (this.currentTypeValueFirst && this.currentTypeValue) {
        params.tagId = this.currentTypeValueFirst + ',' + this.currentTypeValue; //一二级id,不限则传''
      }
      collegeProfessionGetTagScore(params)
        .then((res) => {
          if (res.code == 200) {
            this.matchLevelList = res.data;
            if (res.data.length) {
              this.currentOptionValue = res.data[0].title;
              this.matchMajorNum = res.data[0].num;
              this.contentList = res.data[0].list;
              const totalMatchMajorNum = this.getTotalMatchMajorNum(res.data);
              const avgMatchRate = this.getAvgMatchRate(res.data);
              this.$emit('getTotal', totalMatchMajorNum, avgMatchRate);
            } else {
              this.contentList = [];
            }
          }
        })
        .catch((e) => {
          console.log(e);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getTotalMatchMajorNum(arr) {
      const temp = arr.slice(0, 3);
      return temp.reduce((total, item) => total + parseInt(item.num, 10), 0);
    },
    getAvgMatchRate(arr) {
      let flatArr = [];
      arr.forEach((item) => {
        item.list.forEach((secondItem) => {
          secondItem.children.forEach((thirdItem) => {
            flatArr.push(thirdItem.score);
          });
        });
      });

      let totalScore = 0;
      let count = 0;
      flatArr.forEach((score) => {
        totalScore += score;
        count++;
      });
      return (totalScore / count).toFixed(2);
    },
    //获取专业类别筛选项
    getAllPositionTagTreeList() {
      getAllPositionTagTree({
        cateType: this.currentLevelValue,
        tagType: '10',
        treeType: 1
      })
        .then((res) => {
          if (res.code == 200) {
            this.majorTypeOptions = res.data || [];
          }
        })
        .catch((err) => {});
    }
  }
};
</script>

<style lang="scss" scoped>
.match-major {
  width: 100%;
  height: 1096rpx;
  background: #ffffff;
  padding: 16rpx 18rpx;
  border-radius: 24rpx;
  .filter-list {
    background-color: #ffffff;
    display: flex;
    flex-direction: row;
    align-items: center;
    transition: padding 0.3s ease; // 添加过渡动画
    padding-bottom: 24rpx;
    border-bottom: 2rpx solid #eeeef5;
    .major-level,
    .major-type {
      margin-right: 16rpx;
      width: 158rpx;
      height: 56rpx;
      border-radius: 12rpx;
      position: relative; /* 确保伪元素相对于这个元素定位 */
      display: inline-flex; /* 使元素适应内容 */
      flex-direction: row;
      align-items: center;
      padding: 4rpx 16rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 24rpx;
      color: #888888;
      transition: opacity 0.3s ease; // 添加过渡动画
      &::after {
        content: ''; /* 必须设置内容 */
        position: absolute; /* 绝对定位 */
        bottom: 20rpx; /* 底部对齐 */
        right: 16rpx; /* 右侧对齐 */
        width: 0; /* 宽度为0 */
        height: 0; /* 高度为0 */
        border-width: 10rpx; /* 三角形的大小 */
        border-style: solid; /* 边框样式 */
        border-color: transparent transparent transparent #c0c0c0; /* 三角形颜色，左下角为 #c0c0c0 */
        transform-origin: 0 100%; /* 设置旋转中心点 */
        transform: rotate(45deg); /* 沿 X 轴旋转 -45 度 */
      }
      &.selected {
        color: #f65b3c;
        &::after {
          border-color: transparent transparent transparent#f65b3c;
        }
      }
    }
    .search-major {
      width: 336rpx;
      height: 56rpx;
      background: #f6f6f6;
      border-radius: 12rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 24rpx;
      color: #888888;
      display: flex; /* 使元素适应内容 */
      flex-direction: row;
      align-items: center;
      padding: 4rpx 16rpx;
      transition: width 0.3s ease; // 添加过渡动画
      flex: 1; // 使用 Flex 布局
      &.expanded {
        width: 100%;
      }
    }
  }
  .main {
    &-options {
      margin-top: 30rpx;
      &-list {
        display: flex;
        justify-content: space-between;
        &-item {
          padding: 10rpx 13rpx;
          background: #f6f6f6;
          border-radius: 8rpx;
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 22rpx;
          color: #666666;
          line-height: 32rpx;
          &.selected {
            color: #f65b3c;
            background: #fef0e7;
          }
        }
      }
      &-desc {
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 24rpx;
        color: #f66b4e;
        line-height: 34rpx;
        margin-top: 12rpx;
      }
    }
    &-content {
      &-list {
        display: flex;
        flex-direction: column;
        height: calc(100vh - 880rpx);
        &-item {
          margin-top: 32rpx;
          &:last-of-type {
            padding-bottom: 80rpx;
          }
          .item-title {
            font-family: PingFang-SC, PingFang-SC;
            font-weight: bold;
            font-size: 30rpx;
            color: #222222;
            line-height: 42rpx;
            margin-bottom: 12rpx;
          }
          .item-list {
            display: grid;
            grid-row-gap: 14rpx;
            grid-column-gap: 16rpx;
            grid-template-columns: repeat(3, 1fr);
            &-item {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              background: #f7f7f7;
              border-radius: 8rpx;
              padding: 18rpx 26rpx;
              &-label {
                font-family: PingFang-SC, PingFang-SC;
                font-weight: bold;
                font-size: 28rpx;
                color: #333333;
                line-height: 40rpx;
                text-align: center;
              }
              &-value {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 24rpx;
                color: #999999;
                line-height: 34rpx;
                text-align: center;
              }
            }
          }
        }
      }
      &-empty {
      }
    }
    .introduce-content {
      width: 100%;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 24rpx;
      color: #f66b4e;
      margin-top: 8rpx;
    }
  }
}
</style>
